package com.youan.pangu.core.mvc.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.youan.pangu.base.util.ResponseUtil;
import com.youan.pangu.base.bean.result.AbsResponseBean;
import com.youan.pangu.base.bean.result.SuccessResponse;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;

/**
 * 以固定的格式返回前台数据
 */
public class JsonReturnValueHandler implements HandlerMethodReturnValueHandler {

    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return true;
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        AbsResponseBean responseBean = null;
        if(null == returnValue) {
            responseBean = new SuccessResponse("");
        } else {
            Class clzz = returnValue.getClass();
            if(!clzz.isArray() && clzz.getSuperclass().equals(AbsResponseBean.class)){
                responseBean = (AbsResponseBean) returnValue;
            }else {
                responseBean = new SuccessResponse(returnValue);
            }
        }

        HttpServletResponse response=webRequest.getNativeResponse(HttpServletResponse.class);

        try {
            String responseStr = objectMapper.writeValueAsString(responseBean);
            ResponseUtil.write(response, responseStr);
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            mavContainer.setRequestHandled(true);
        }
    }
}
